﻿// ----------------------------------------------------------------------
// <author name="Moses Kehengu"/>
// <copyright file="FacilityManagement.cs" company="Futures Group International">
//     Copyright statement. All right reserved
// </copyright>
//
// ------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GenericTools;
using System.Data;
using System.Data.Common;
using System.Windows.Forms;
using Telerik.WinControls.UI;
using Telerik.WinControls.UI.Export;
using System.Drawing;
using DataModels.Enumerations;
using DataModels.Common;

namespace ReportingManagement
{
    public partial class MainWindow
    {
        private bool tabPageFacilityManagementLoaded = false;
        private DataTable facilities = null;

        private void PopulateFacilities()
        {
            Cursor.Current = Cursors.WaitCursor;
            toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
            switch (this.authenticatedUser.Level)
            {
                case AccessLevel.ADMINISTRATOR:
                    //facilities = Utilities.GetAllFacilities();
                    facilities = Utilities.GetAllFacilitiesStatus();
                    break;

                case AccessLevel.NATION:
                    //facilities = Utilities.GetAllFacilities();
                    facilities = Utilities.GetAllFacilitiesStatus(this.authenticatedUser.SupportingPartnerId);
                    break;

                case AccessLevel.REGION:
                    int regionID = Int32.Parse(this.authenticatedUser.AccessLevelValue);
                    facilities = Utilities.GetAllRegionFacilitiesStatus(regionID, this.authenticatedUser.SupportingPartnerId);
                    break;

                case AccessLevel.DISTRICT:
                    int districtID = Int32.Parse(this.authenticatedUser.AccessLevelValue);
                    facilities = Utilities.GetAllDistrictFacilitiesStatus(districtID);
                    break;

                case AccessLevel.FACILITY:
                    string facilityCode = this.authenticatedUser.AccessLevelValue;
                    facilities = Utilities.GetFacilityStatus(facilityCode);
                    break;
            }
            Cursor.Current = Cursors.Default;
            toolStripStatusLabel.Text = "Ready";
            
            int trainedFacilities = 0;
            foreach (DataRow row in facilities.Rows)
            {
                bool trained = bool.Parse(row["Trained"].ToString());
                if (trained) trainedFacilities++;
            }

            if (trainedFacilities > 1)
            {
                int halfFacilityCount = facilities.Rows.Count / 2;

                lblTrainedFacilities.Text = String.Format("{0} facilities are trained for sending reports", trainedFacilities);
                if (trainedFacilities > halfFacilityCount) lblTrainedFacilities.ForeColor = System.Drawing.Color.Blue;
                else lblTrainedFacilities.ForeColor = System.Drawing.Color.Brown;
            }
            else
            {
                if (trainedFacilities == 0)
                {
                    lblTrainedFacilities.Text = "There is no facility trained for sending reports";
                    lblTrainedFacilities.ForeColor = System.Drawing.Color.Red;
                }
                else
                {
                    lblTrainedFacilities.Text = String.Format("{0} facility is trained for sending reports", trainedFacilities);
                    lblTrainedFacilities.ForeColor = System.Drawing.Color.Brown;
                }
            }

            //dgvFacilities.DataSource = dataTable;
            //lblCount.Text = String.Format("There are {0} facilities.", dgvFacilities.Rows.Count);
            try
            {
                facilities.Columns.Remove("SupportingPartnerId");
            }
            catch { }

            radGridView1.DataSource = facilities;
            //GridViewTextBoxColumn facilityCodeColumn = new GridViewTextBoxColumn("Facility Code");
            //GridViewTextBoxColumn facilityNameColumn = new GridViewTextBoxColumn("Facility Name");
            //GridViewTextBoxColumn statusColumn = new GridViewTextBoxColumn("Status");
            //GridViewTextBoxColumn districtNameColumn = new GridViewTextBoxColumn("District Name");
            //GridViewTextBoxColumn regionNameColumn = new GridViewTextBoxColumn("Region Name");
            //radGridView1.MasterTemplate.Columns.Clear();
            //radGridView1.MasterTemplate.Columns.Add(facilityCodeColumn);
            //radGridView1.MasterTemplate.Columns.Add(facilityNameColumn);
            //radGridView1.MasterTemplate.Columns.Add(statusColumn);
            //radGridView1.MasterTemplate.Columns.Add(districtNameColumn);
            //radGridView1.MasterTemplate.Columns.Add(regionNameColumn);
            //foreach (DataRow row in facilities.Rows)
            //{
            //    GridViewRowInfo rowInfo = radGridView1.Rows.AddNew();
            //    rowInfo.Cells[0].Value = row[0];
            //    rowInfo.Cells[1].Value = row[1];
            //    rowInfo.Cells[2].Value = row[2];
            //    rowInfo.Cells[3].Value = row[3];
            //    rowInfo.Cells[4].Value = row[4];
            //}

            radGridView1.MasterTemplate.AutoSizeColumnsMode = Telerik.WinControls.UI.GridViewAutoSizeColumnsMode.Fill;

            if (radGridView1.Rows.Count > 1)
            {
                lblCount.Text = String.Format("There are {0} facilities.", radGridView1.Rows.Count);
            }
            else
            {
                lblCount.Text = String.Format("There is {0} facility.", radGridView1.Rows.Count);
            }
        }

        private void dgvFacilities_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                try
                {
                    DataGridViewRow row = dgvFacilities.Rows[e.RowIndex];
                    DataGridViewCell cell = row.Cells[0];
                    string facility = cell.Value.ToString();

                    bool canEdit = default(bool);
                    if (this.authenticatedUser.Level == AccessLevel.ADMINISTRATOR
                        || this.authenticatedUser.Level == AccessLevel.NATION)
                    {
                        canEdit = true;
                    }
                    else
                    {
                        canEdit = false;
                    }

                    FacilityDetailsForm facilityDetails = new FacilityDetailsForm(facility, canEdit, this.authenticatedUser);
                    DialogResult response = facilityDetails.ShowDialog(this);
                    if (response == DialogResult.OK)
                    {
                        PopulateFacilities();
                        tabPageSMSReminderLoaded = false;   // reload SMS reminder tab
                    }
                }
                catch (Exception ex)
                {
                    DisplayErrorMessage(ex);
                }
            }
        }

        private void radGridView1_CellDoubleClick(object sender, Telerik.WinControls.UI.GridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                GridViewRowInfo row = radGridView1.Rows[e.RowIndex];
                EditFacilityDetails(row);
            }
        }

        private void btnEditFacility_Click(object sender, EventArgs e)
        {
            if (radGridView1.SelectedRows.Count > 0)
            {
                GridViewRowInfo row = radGridView1.SelectedRows[0];
                EditFacilityDetails(row);
            }
            else
            {
                MessageBox.Show(this, "Please select a facility to be edited!", AppConfiguration.ApplicationName,
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void EditFacilityDetails(GridViewRowInfo row)
        {
            try
            {
                GridViewCellInfo cell = row.Cells[0];
                string facility = cell.Value.ToString();

                bool canEdit = default(bool);
                if (this.authenticatedUser.Level == AccessLevel.ADMINISTRATOR
                    || this.authenticatedUser.Level == AccessLevel.NATION)
                {
                    canEdit = true;
                }
                else
                {
                    canEdit = false;
                }

                Cursor.Current = Cursors.WaitCursor;
                FacilityDetailsForm facilityDetails = new FacilityDetailsForm(facility, canEdit, this.authenticatedUser);
                Cursor.Current = Cursors.Default;
                DialogResult response = facilityDetails.ShowDialog(this);
                if (response == DialogResult.OK)
                {
                    //PopulateFacilities();
                    if (facilityDetails.Updated)
                    {
                        if (facilityDetails.Added)
                        {
                            DataRow r = facilities.NewRow();
                            r[0] = facilityDetails.FacilityCode;
                            r[1] = facilityDetails.FacilityName;
                            r[2] = (facilityDetails.Active) ? "ACTIVE" : "INACTIVE";
                            r[3] = facilityDetails.DistrictName;
                            r[4] = facilityDetails.RegionName;
                            r["Trained"] = facilityDetails.Trained;
                            //r["SupportingPartnerId"] = facilityDetails.SupportingPartnerId;
                            r["Supporting Partner"] = facilityDetails.SupportingPartner;
                            facilities.Rows.Add(r);
                            //radGridView1.DataSource = facilities;
                        }
                        else
                        {
                            int index = radGridView1.CurrentRow.Index;
                            for (int i = 0; i < facilities.Columns.Count; i++) facilities.Columns[i].ReadOnly = false;

                            DataRowView r = (DataRowView)row.DataBoundItem;
                            //DataRow r = facilities.Rows[index];
                            r[0] = facilityDetails.FacilityCode;
                            r[1] = facilityDetails.FacilityName;
                            r[2] = (facilityDetails.Active) ? "ACTIVE" : "INACTIVE";
                            r[3] = facilityDetails.DistrictName;
                            r[4] = facilityDetails.RegionName;
                            r["Trained"] = facilityDetails.Trained;
                            //r["SupportingPartnerId"] = facilityDetails.SupportingPartnerId;
                            r["Supporting Partner"] = facilityDetails.SupportingPartner;
                            //radGridView1.DataSource = facilities;
                            lblCount.Text = String.Format("There are {0} facilities.", radGridView1.Rows.Count);
                        }
                    }
                    if (facilityDetails.Deleted)
                    {
                        //int index = radGridView1.CurrentRow.Index;
                        //facilities.Rows.RemoveAt(index);
                        //radGridView1.DataSource = facilities;
                        DataRowView rowView = row.DataBoundItem as DataRowView;
                        if (rowView != null) rowView.Delete();
                        lblCount.Text = String.Format("There are {0} facilities.", radGridView1.Rows.Count);
                    }

                    int trainedFacilities = 0;
                    foreach (DataRow r in facilities.Rows)
                    {
                        if (r.RowState != DataRowState.Deleted)
                        {
                            bool trained = false;
                            if (bool.TryParse(r["Trained"].ToString(), out trained))
                            {
                                if (trained) trainedFacilities++;
                            }
                        }
                    }

                    if (trainedFacilities > 1)
                    {
                        int halfFacilityCount = facilities.Rows.Count / 2;

                        lblTrainedFacilities.Text = String.Format("{0} facilities are trained for sending reports", trainedFacilities);
                        if (trainedFacilities > halfFacilityCount) lblTrainedFacilities.ForeColor = System.Drawing.Color.Blue;
                        else lblTrainedFacilities.ForeColor = System.Drawing.Color.Brown;
                    }
                    else
                    {
                        if (trainedFacilities == 0)
                        {
                            lblTrainedFacilities.Text = "There is no facility trained for sending reports";
                            lblTrainedFacilities.ForeColor = System.Drawing.Color.Red;
                        }
                        else
                        {
                            lblTrainedFacilities.Text = String.Format("{0} facility is trained for sending reports", trainedFacilities);
                            lblTrainedFacilities.ForeColor = System.Drawing.Color.Brown;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                DisplayErrorMessage(ex);
            }
        }

        private void btnAddNewFacility_Click(object sender, EventArgs e)
        {
            if ((AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DATA_ACCESS) ||
                (AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DIRECT_ACCESS))
            {
                string message = @"The application is running in offline mode. " +
                    "You can not perform any activities that require server " +
                    "connection while you are offline. " +
                    "\n\nYou are current operation will not be processed!";
                MessageBox.Show(this, message, AppConfiguration.ApplicationName,
                    MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }

            try
            {
                FacilityDetailsForm facilityDetails = new FacilityDetailsForm(this.authenticatedUser);
                DialogResult response = facilityDetails.ShowDialog(this);
                if (response == DialogResult.OK)  
                {
                    DataRow r = facilities.NewRow();
                    r[0] = facilityDetails.FacilityCode;
                    r[1] = facilityDetails.FacilityName;
                    r[2] = (facilityDetails.Active) ? "ACTIVE" : "INACTIVE";
                    r[3] = facilityDetails.DistrictName;
                    r[4] = facilityDetails.RegionName;
                    r["Trained"] = facilityDetails.Trained;         // Trained
                    //r[6] = facilityDetails.SupportingPartnerId;
                    r["Supporting Partner"] = facilityDetails.SupportingPartner;
                    facilities.Rows.Add(r);
                    radGridView1.DataSource = facilities;

                    //GridViewRowInfo r = radGridView1.Rows.AddNew();
                    //r.Cells[0].Value = facilityDetails.FacilityCode;
                    //r.Cells[1].Value = facilityDetails.FacilityName;
                    //r.Cells[2].Value = (facilityDetails.Active) ? "ACTIVE" : "INACTIVE";
                    //r.Cells[3].Value = facilityDetails.DistrictName;
                    //r.Cells[4].Value = facilityDetails.RegionName;
                    //radGridView1.Rows.Add(r);
                    lblCount.Text = String.Format("There are {0} facilities.", radGridView1.Rows.Count);
                }
            }
            catch (Exception ex)
            {
                DisplayErrorMessage(ex);
            }
        }

        private void btnExportFacilitiesToExcel_Click(object sender, EventArgs e)
        {
            CreateExcelExportFile(this.facilities);
            //DialogResult response = saveFileDialog.ShowDialog(this);
            //if (response == System.Windows.Forms.DialogResult.OK)
            //{
            //    try
            //    {
            //        string filename = saveFileDialog.FileName;
            //        ExportToExcelML exporter = new ExportToExcelML(radGridView1);
            //        exporter.SheetName = "List of Facilities";
            //        exporter.RunExport(filename);
            //        exporter = null;
            //        MessageBox.Show(this,
            //            "Data Export completed successfully",
            //            AppConfiguration.ApplicationName,
            //            MessageBoxButtons.OK, MessageBoxIcon.Information);
            //        return;
            //    }
            //    catch (Exception ex)
            //    {
            //        MessageBox.Show(this, ex.Message, AppConfiguration.ApplicationName,
            //            MessageBoxButtons.OK, MessageBoxIcon.Error);
            //        return;
            //    }
            //}
        }

        private void tabPageFacilityManagement_Enter(object sender, EventArgs e)
        {
            if (!tabPageFacilityManagementLoaded)
            {
                try
                {
                    // we are using different control but the old one should still be there.
                    // who knows I might need it in the future.
                    dgvFacilities.Enabled = false;
                    dgvFacilities.Visible = false;

                    PopulateFacilities();
                    if (this.authenticatedUser.Level == AccessLevel.ADMINISTRATOR
                        || this.authenticatedUser.Level == AccessLevel.NATION)
                    {
                        btnAddNewFacility.Enabled = true;
                    }
                    else
                    {
                        btnAddNewFacility.Enabled = false;
                    }
                    tabPageFacilityManagementLoaded = true;
                }
                catch (Exception ex)
                {
                    DisplayErrorMessage(ex);
                }
            }
        }

        private void btnShowRegisteredUsers_Click(object sender, EventArgs e)
        {
            if (radGridView1.SelectedRows.Count > 0)
            {
                try
                {
                    GridViewRowInfo row = radGridView1.SelectedRows[0];
                    GridViewCellInfo cell = row.Cells[0];
                    string facility = cell.Value.ToString();

                    FacilityRegisteredUsers facilityRegisteredUsers = new FacilityRegisteredUsers(facility);
                    facilityRegisteredUsers.ShowDialog(this);
                }
                catch (Exception ex)
                {
                    DisplayErrorMessage(ex);
                }
            }
            else
            {
                MessageBox.Show(this, "Please select a facility to be edited!", AppConfiguration.ApplicationName,
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void txtSearchFacility_TextChanged(object sender, EventArgs e)
        {
            string keyword = txtSearchFacility.Text;
            DataTable dataSource = radGridView1.DataSource as DataTable;
            if (dataSource != null)
            {
                if (string.IsNullOrEmpty(keyword))
                {
                    // Reset everything back to the way it was.
                    dataSource.DefaultView.RowFilter = string.Empty;
                    string format = dataSource.DefaultView.Count > 1 ? "There are {0} facilities." : "There is {0} facility.";
                    lblCount.Text = string.Format(format, dataSource.DefaultView.Count);
                    lblCount.ForeColor = Color.Black;
                    return;
                }

                string filterExpression = string.Format(
                    "[Facility Name] LIKE '%{0}%' " + 
                    "OR [Facility Code] LIKE '%{0}%' " +
                    "OR [District Name] LIKE '%{0}%'", keyword);

                // First we search the facility name
                dataSource.DefaultView.RowFilter = filterExpression;
                string format2 = dataSource.DefaultView.Count > 1 ? "Search Results: {0} facilities" : "Search Results: {0} facility";
                lblCount.Text = string.Format(format2, dataSource.DefaultView.Count);
                lblCount.ForeColor = Color.BlueViolet;
            }
        }
    }
}
